"use client";

import { useState, useRef } from "react";
import Image from "next/image";
import { CarImage } from "@/types";

interface CarImageGalleryProps {
  images: CarImage[];
  currentIndex: number;
  onIndexChange: (index: number) => void;
}

export default function CarImageGallery({
  images,
  currentIndex,
  onIndexChange,
}: CarImageGalleryProps) {
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [showMagnifier, setShowMagnifier] = useState(false);
  const [magnifierPosition, setMagnifierPosition] = useState({ x: 0, y: 0 });
  const imageRef = useRef<HTMLDivElement>(null);

  const nextImage = () => {
    onIndexChange((currentIndex + 1) % images.length);
  };

  const prevImage = () => {
    onIndexChange((currentIndex - 1 + images.length) % images.length);
  };

  const goToImage = (index: number) => {
    onIndexChange(index);
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (!imageRef.current) return;
    
    const { left, top, width, height } = imageRef.current.getBoundingClientRect();
    const x = ((e.clientX - left) / width) * 100;
    const y = ((e.clientY - top) / height) * 100;
    
    setMagnifierPosition({ x, y });
  };

  const handleMouseEnter = () => {
    setShowMagnifier(true);
  };

  const handleMouseLeave = () => {
    setShowMagnifier(false);
  };

  return (
    <div className="relative">
      {/* 主图展示 */}
      <div 
        ref={imageRef}
        className="relative aspect-[4/3] rounded-lg overflow-hidden bg-gray-100"
        onMouseMove={handleMouseMove}
        onMouseEnter={handleMouseEnter}
        onMouseLeave={handleMouseLeave}
      >
        {images.length > 0 ? (
          <>
            <Image
              src={images[currentIndex].url}
              alt="car"
              fill
              className="object-cover cursor-pointer"
              onClick={() => setIsFullscreen(true)}
            />
            
            {/* 放大镜效果 */}
            {showMagnifier && (
              <div className="absolute inset-0 pointer-events-none">
                {/* 半透明选择区域 - 跟随鼠标移动 */}
                <div 
                  className="absolute w-32 h-32 border-2 border-white rounded-lg shadow-lg  backdrop-blur-sm"
                  style={{
                    left: `${magnifierPosition.x}%`,
                    top: `${magnifierPosition.y}%`,
                    transform: 'translate(-50%, -50%)',
                  }}
                />
                {/* 放大镜预览区域 - 放在图片右侧，跟随鼠标垂直位置 */}
                <div 
                  className="z-[999] absolute left-[calc(100%+16px)] w-80 h-80 border-2 border-gray-300 rounded-lg  shadow-2xl "
                  style={{
                    top: `${magnifierPosition.y}%`,
                    transform: 'translateY(-50%)',
                  }}
                >
                  <div 
                    className="w-full h-full"
                    style={{
                      backgroundImage: `url(${images[currentIndex].url})`,
                      backgroundSize: `${(imageRef.current?.clientWidth || 800) * 2}px ${(imageRef.current?.clientHeight || 600) * 2}px`,
                      backgroundPosition: `${magnifierPosition.x * 2}% ${magnifierPosition.y * 2}%`,
                      backgroundRepeat: 'no-repeat',
                    }}
                  />
                </div>
              </div>
            )}
          </>
        ) : (
          <div className="flex items-center justify-center h-full">
            <div className="text-6xl text-gray-400">🚗</div>
          </div>
        )}

        {/* 左右切换按钮 */}
        {images.length > 1 && (
          <>
            <button
              onClick={prevImage}
              className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M15 19l-7-7 7-7"
                />
              </svg>
            </button>
            <button
              onClick={nextImage}
              className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
            >
              <svg
                className="w-6 h-6"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </button>
          </>
        )}

        {/* 图片指示器 */}
        {images.length > 1 && (
          <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2 flex space-x-2">
            {images.map((_, index) => (
              <button
                key={index}
                onClick={() => goToImage(index)}
                className={`w-3 h-3 rounded-full transition-all ${
                  index === currentIndex
                    ? "bg-white"
                    : "bg-white/50 hover:bg-white/70"
                }`}
              />
            ))}
          </div>
        )}

        {/* 全屏按钮 */}
        <button
          onClick={() => setIsFullscreen(true)}
          className="absolute top-4 right-4 bg-black/50 text-white p-2 rounded-full hover:bg-black/70 transition-colors"
        >
          <svg
            className="w-5 h-5"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4"
            />
          </svg>
        </button>
      </div>

      {/* 缩略图列表 */}
      {images.length > 1 && (
        <div className="grid grid-cols-4 gap-2 mt-4">
          {images.map((image, index) => (
            <button
              key={image.id}
              onClick={() => goToImage(index)}
              className={`relative aspect-video rounded overflow-hidden border-2 transition-all ${
                index === currentIndex
                  ? "border-blue-500"
                  : "border-transparent hover:border-gray-300"
              }`}
            >
              <Image
                src={image.url}
                alt="car"
                fill
                className="object-cover"
              />
            </button>
          ))}
        </div>
      )}

      {/* 全屏模态框 */}
      {isFullscreen && images.length > 0 && (
        <div className="fixed inset-0 bg-black z-50 flex items-center justify-center">
          <div className="relative w-full h-full flex items-center justify-center">
            <Image
              src={images[currentIndex].url}
              alt="car"
              fill
              className="object-contain"
            />

            {/* 关闭按钮 */}
            <button
              onClick={() => setIsFullscreen(false)}
              className="absolute top-4 right-4 text-white p-2 rounded-full hover:bg-white/20 transition-colors"
            >
              <svg
                className="w-8 h-8"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>

            {/* 全屏切换按钮 */}
            {images.length > 1 && (
              <>
                <button
                  onClick={prevImage}
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 text-white p-3 rounded-full hover:bg-white/20 transition-colors"
                >
                  <svg
                    className="w-8 h-8"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15 19l-7-7 7-7"
                    />
                  </svg>
                </button>
                <button
                  onClick={nextImage}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-white p-3 rounded-full hover:bg-white/20 transition-colors"
                >
                  <svg
                    className="w-8 h-8"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M9 5l7 7-7 7"
                    />
                  </svg>
                </button>
              </>
            )}

            {/* 全屏指示器 */}
            {images.length > 1 && (
              <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex space-x-3">
                {images.map((_, index) => (
                  <button
                    key={index}
                    onClick={() => goToImage(index)}
                    className={`w-4 h-4 rounded-full transition-all ${
                      index === currentIndex
                        ? "bg-white"
                        : "bg-white/50 hover:bg-white/70"
                    }`}
                  />
                ))}
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
